package com.sc.socket.udpgroup;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author shuc001
 * @Date 2019-02-02 23:26
 */
public class Search {
    public static final int LISTEN_PORT = 30000;

    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println("start");
        SearchThread listen = listen();
        sendBroadCast();
        System.in.read();
        List<Device> devices = listen.getDevices();
        for (Device device : devices) {
            System.out.println(device.toString());
        }
        System.out.println("finish");
    }


    private static SearchThread listen() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        SearchThread st = new SearchThread(LISTEN_PORT,countDownLatch);
        st.start();
        countDownLatch.await();
        return st;
    }

    private static void sendBroadCast() throws IOException {
        DatagramSocket ds = new DatagramSocket();
        //构建会送数据
        String resp = MessageCreator.buildWithPort(LISTEN_PORT);
        byte[] res =  resp.getBytes();
        DatagramPacket response = new DatagramPacket(res, res.length);
        //广播
        response.setAddress(InetAddress.getByName("255.255.255.255"));
        response.setPort(20000);
        ds.send(response);
        ds.close();
        System.out.println("send finish");
    }


    private static class Device{
        private int port;
        private String ip;
        private String sn;

        private Device(int port,String ip,String sn){
            this.port=port;
            this.ip=ip;
            this.sn=sn;
        }

        @Override
        public String toString() {
            return "Device{" +
                    "port=" + port +
                    ", ip='" + ip + '\'' +
                    ", sn='" + sn + '\'' +
                    '}';
        }
    }

    private static class SearchThread extends Thread{

        private final int listenPort;
        private final CountDownLatch countDownLatch;
        private List<Device> devices = new ArrayList<>();
        private boolean done = false;
        private DatagramSocket ds = null;

        private SearchThread(int listenPort, CountDownLatch countDownLatch) {
            this.listenPort = listenPort;
            this.countDownLatch = countDownLatch;
        }
        @Override
        public void run() {
            countDownLatch.countDown();
            try{
                ds = new DatagramSocket(listenPort);
                while (!done){
                    final  byte[] buf = new byte[512];
                    DatagramPacket packet = new DatagramPacket(buf,buf.length);

                    ds.receive(packet);
                    String ip = packet.getAddress().getHostAddress();
                    int port = packet.getPort();
                    int dataLen = packet.getLength();

                    String data = new String(packet.getData(),0,dataLen);
                    System.out.println(ip+port+"   "+data);
                    String sn = MessageCreator.parseSN(data);

                    if(sn!=null){
                        Device device = new Device(port,ip,sn);
                        devices.add(device);

                    }

                }
            }catch (Exception e){

            }finally {
                close();
            }

        }


        private void close(){
            if(ds!=null){
                ds.close();
                ds=null;
            }
        }

        List<Device> getDevices(){
            done=true;
            close();
            return devices;
        }
    }
}
